import { _decorator, Component, director, Node, UITransform, Sprite, SpriteFrame, resources, view, Prefab, instantiate, Button, sys, game, Tween, find } from 'cc';
const { ccclass, property } = _decorator;
import UtilTool from '../tools/UtilTool';
import {ENV, init} from '../common/web3/index';
import { signRandom , login as loginAccount ,version, getPublicKey} from '../net/Fetch';
import wsTool from '../net/ws';
import { App } from '../App';
import { EventConst } from '../common/Common';
import { LoadMg } from '../tools/LoadMg';
import Config from '../common/Config';
import CommConst from '../const/CommConst';
import { Req_GP_Logon, Resp_GP_LogonSuccess } from '../proto/login.proto';
import { SetChainPanel } from './SetChainPanel';
import { PD } from '../player/PlayerData';
import { sp } from 'cc';


@ccclass('Login')
export class Login extends Component {

    @property(Prefab)
    loadingBox: Prefab = null;
    
    start() {
        this.node.getComponent(UITransform).setContentSize(view.getVisibleSize())
        LoadMg.loadPrefab = this.loadingBox;
        LoadMg.removeLoad()

        UtilTool.setPos(find("bg",this.node), [0, 1])
        UtilTool.preloadScene('home');
        // UtilTool.preloadScene('game2');
        UtilTool.preloadScene('game3');
        UtilTool.preloadScene('game4');
        UtilTool.preloadScene('game5');

        UtilTool.preloadScene('game1');
        UtilTool.preloadScene('multiroom');
        UtilTool.preloadScene('multiselect');
        UtilTool.preloadScene('bloodselect');

        /* new Tween(this.node).delay(2).call(() => {
            App.Scene.go('test')
        }).start() */

        // 下面这段是为了能直接改H5网址的myLink的值来切换服务器地址
        let link:string = window.location.href // http://192.168.31.229:7700/web-mobile/billiards/index.html?myLink=http://192.168.31.197:8080|ws://
        let param1 = link.indexOf("myLink")
        if (param1 != -1) {
            let value = link.split("?")[1].split("=")[1]
            if (value) {
                App.hrefLinkIp = value.split("|")[0]
                App.hrefLinkWs = value.split("|")[1]
            }
        }

        //spine test
        let self = this
        resources.load("spine/welfare center",sp.SkeletonData,function(err, spine){
            if (err) {
                console.log(err.message || err)
                return
            }

            let node = new Node("spineNode")
            let ske = node.addComponent(sp.Skeleton)
            ske.skeletonData = spine
            ske.premultipliedAlpha = false
            ske.setAnimation(0, "animation0", true)
            self.node.addChild(node)
        })
        
    }
    
    update(deltaTime: number) {
        
    }

    // 点击选择不同链
    clickLogin(event: Event, customEventData: string) {
        
        if (customEventData=="btn1") {
            this.login(0)
        }
        
    }

    // 登录
    async login(chainIndex){
        PD.user.chainIndex = chainIndex
        LoadMg.showLoad({type:1})
        let web3 = init(Config.CONTRACTENV);//web3初始化，不初始化无法调用任何区块链的东西

        try {
            let publicKeyData = await getPublicKey();  //获取公钥
            if (publicKeyData.ret == 0) {
                App.publicKey = publicKeyData.publicKey
                App.isEncrypt = publicKeyData.usingCipherText
            }
             
            // signRandom 签名接口 
            // loginWallet 
            let loginRes = await web3.login({chainIndex,signRandom,loginWallet:loginAccount}); //登录
            if (loginRes.ret == 0) {
                PD.user.addressUrl = localStorage.getItem('userWalletAddress')
                let versionData = await version(); 
                wsTool.init(versionData.gateUrl)
                .then(async res =>{
                    try {
                        UtilTool.printLog('open成功');
                        App.GlobalConfig.init()
                        App.init()
                        PD.init()

                        // let gpLogon:Req_GP_Logon = new Req_GP_Logon();
                        // let buf = gpLogon.decode(loginRes.userId, loginRes.token);

                        wsTool.send({"msgCode":CommConst.Req_LOGIN,"token":loginRes.token,"userId":loginRes.userId})
                        .then(res =>{
                            if (res?.result == 0) {
                                PD.setplayerInfo(res)
                                PD.user.token = loginRes.token

                                LoadMg.showLoad({type:1})
                                App.Scene.goHome('home',null,() =>{
                                    // LoadMg.removeLoad()
                                })
                            }else{
                                // LoadMg.removeLoad()
                                alert('网络连接失败')
                            }
                        })
                    } catch (error) {
                            UtilTool.printLog(error,'xxxxx');
                            
                    }
                })
                .catch(err =>{
                    LoadMg.removeLoad()
                })
            }
        } catch (error) {
            UtilTool.printLog(error,'error');
            LoadMg.removeLoad();
        }
    }

    onDestroy() {
    }
}

    

